import {PROMPT} from '@/constant/prompt';

const TIMEOUT_DURATION = 5000; // 请求超时时间(ms)
export const RESP_METHOD = {
    GET: 'GET',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
};
export const RESP_STATUS = {
    SUCCESS: 200,
    SERVE_ERR: 500,
    AUTH_FAIL: 401,
};

export default class FetchRequest {
    static requestTimeout(reject) {
        setTimeout(() => {
            reject({msg: PROMPT.OVER_TIME});
        }, TIMEOUT_DURATION);
    }
    static setHeaders() {
        return {
            'Accept': 'application/json',
            'Content-Type':'application/json',
        };
    }
    static request(method, url, params, headers = FetchRequest.setHeaders()) {
        return new Promise((resolve, reject) => {
            FetchRequest.requestTimeout(reject);
            let content = {
                method,
                headers,
            };
            if (method !== RESP_METHOD.GET && params) {
                content = {
                    ...content,
                    body: JSON.stringify(params),
                };
            }
            fetch(url, content).then(async (resp) => {
                const status = resp.status;
                const jsonData = await resp.json();
                if (status !== RESP_STATUS.SUCCESS) {
                    reject(jsonData);
                }
                resolve(jsonData);
            }).catch((err) => {
                reject(err);
            });
        });
    }
}
